package skean.apclient;

import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.os.IBinder;
import android.widget.Toast;

public class ScanService extends Service {
	private WifiAdmin admin;

	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		int result = super.onStartCommand(intent, flags, startId);
		admin = new WifiAdmin(this);
		admin.openWifi();
		admin.startScan();
		List<ScanResult> results = admin.getAllScanResult();
		boolean haveExactSSID = false;
		for (ScanResult scanResult : results) {
			if (scanResult.SSID.equals("dpcap01")) {
				haveExactSSID = true;
			}
		}
		if (!haveExactSSID) {
			Toast.makeText(this, "没扫描指定热点", Toast.LENGTH_SHORT).show();
			return result;
		}
		String ssid = admin.getSSID();
		if (ssid.equals("\"" + "dpcap01" + "\"")) {
			Toast.makeText(this, "找到指定热点, 热点已连接", Toast.LENGTH_SHORT).show();
			return result;
		}
		WifiConfiguration targetConfiguration = null;
		if ((targetConfiguration = admin.IsExsits("dpcap01")) != null) {
			Toast.makeText(this, "找到指定热点, 热点未连接, 热点已保存, 连接中", Toast.LENGTH_SHORT).show();
			int targetNetId = targetConfiguration.networkId;
			admin.connectExcat(targetNetId);
		}
		else {
			Toast.makeText(this, "找到指定热点, 热点未连接, 热点未保存, 创建连接中", Toast.LENGTH_SHORT).show();
			targetConfiguration = admin.createConfig();
			int targetNetId = admin.addNetwork(targetConfiguration);
			admin.connectExcat(targetNetId);
		}
		return result;

	}
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

}
